package su.msk.jet.team01.chatik.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import su.msk.jet.team01.chatik.server.data.Client;
import su.msk.jet.team01.chatik.server.data.Feedback;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;

public class NetworkClient implements Feedback {
	
	private static Logger logger = LoggerFactory.getLogger(NetworkClient.class);

	private final Socket socket;
	private final Client client;
	
	private ClientInputHandler input;
	private ClientOutputHandler output;
	
	public NetworkClient(Socket socket) {
		this.socket = socket;
		
		client = new Client(this);
		
		try {
			output = new ClientOutputHandler(socket.getOutputStream(), this);
			input = new ClientInputHandler(socket.getInputStream(), this);
		} catch (SocketException ex) {
			logger.warn(ex.getMessage(), ex);
			close();
		} catch (IOException ex) {
			logger.warn(ex.getMessage(), ex);
			close();
		}
	}
	
	public final Client getClient() {
		return client;
	}
	
	public final void close() {
		client.destroy();
		
		try {
			input.close();
			output.close();
			socket.close();
		} catch (Exception ex) {
			logger.warn("Closing connection error.", ex);
		}
	}
	
	public void disconnect() {
		close();
	}
	
	public String getIP() {
		String orig = socket.getRemoteSocketAddress().toString();
		return orig.substring(1, orig.length());
	}
	
	public void startHandlers() {
		(new Thread(input)).start();
		(new Thread(output)).start();
	}
	
	public void sendMessage(String msg) {
		output.sendMessage(msg);
	}
}
